<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-date"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" ref="addForm">
                    <el-form-item label="问卷名称" :label-width="formLabelWidth" prop="name">
                        <el-input type="text" v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="问卷描述" :label-width="formLabelWidth">
                        <el-input type="text" v-model="addForm.description" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-input placeholder="输入搜索内容" class="search" v-model="searchKey"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="addType">新增问卷</el-button>
        </div>
        <div class="handle-box">
          <el-dialog :title="title" :visible.sync="dialogFormAddVisible">
            <el-form :model="addOptions" :rules="subRules" ref="addForm">
                <el-form-item label="题目标题" :label-width="formLabelWidth" prop="name">
                    <el-input type="text" v-model="addOptions.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="题目类型" :label-width="formLabelWidth" prop="qTypeId">
                  <el-select v-model="addOptions.qTypeId" placeholder="请选择">
                      <el-option
                          v-for="item in types"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否必填" :label-width="formLabelWidth" prop="isAnswerRequired">
                  <el-select v-model="addOptions.isAnswerRequired" placeholder="请选择">
                      <el-option
                          v-for="item in requireds"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="题目序号" :label-width="formLabelWidth" prop="orderNumber">
                  <el-input type="number" v-model="addOptions.orderNumber" auto-complete="off">
                  </el-input>
                </el-form-item>
                <el-form-item label="题目选项" :label-width="formLabelWidth">
                  <div class="options" v-model="addOptions.options" v-for="(item, index) in options" :key="index">
                    <el-input type="text" v-model="item.content" auto-complete="off">
                    </el-input>
                    <el-button type="text" size="small" @click="deleSubject(index)">删除</el-button>
                  </div>
                  <el-button type="text" size="small" @click="addSubject()">
                    添加
                  </el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSubject">确 定</el-button>
            </div>
          </el-dialog>
        </div>
        <div>
          <el-table :data="dataSource" border fit style="width: 100%">
            <el-table-column prop="name" label="名称" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="description" label="问卷描述" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="state" label="状态" show-overflow-tooltip empty-text :formatter="stateFormatter">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                  <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
                  <el-button type="text" size="small" @click="subject(scope.row)">新增题目</el-button>
                  <el-button type="text" size="small" @click="editSubject(scope.row)">题目列表</el-button>
                  <el-button type="text" size="small" @click="delNotice(scope.row)">删除</el-button>
                  <el-switch
                    v-model="scope.row.state === 1 ? true : false"
                    active-color="#13ce66"
                    @change="switchChange(scope.row)"
                  >
                  </el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination @current-change="handleCurrentChange" :current-page="page.number" 
          layout="total, prev, pager, next, jumper" :total="page.total">
          </el-pagination>
        </div>
    </div>
</template>
<script>
import { questionnaire } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
const { listApi, addApi, updateApi, deleteApi, disableApi,
listTypeAllApi, addSubjectForQuestionApi } = questionnaire
export default {
    data() {
        return {
            dialogFormVisible: false,
            dialogFormAddVisible: false,
            title: '',
            addForm: {},
            addOptions: {},
            formLabelWidth: '120px',
            searchKey: '',
            rules: {
                name: [{ required: true, message: '请输入问卷名称', trigger: 'blur' }],
            },
            subRules: {
                name: [{ required: true, message: '请输入题目', trigger: 'blur' }],
                qTypeId: [{ required: true, message: '请选择题目类型', trigger: 'blur' }],
                isAnswerRequired: [{ required: true, message: '请选择是否必填', trigger: 'blur' }],
                orderNumber: [{ required: true, message: '请输入题目序号', trigger: 'blur' }]
            },
            requireds: [{
              value: 1,
              label: '是'
            }, {
              value: 0,
              label: '否'
            }],
            currentId: '',
            //题目数组
            // optionsItem: {code: '', content: ''},
            options: [],
            codes: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
            'U', 'V', 'W', 'X', 'Y', 'Z']
        }
    },
    created() { 
        this.allType(1)
        this.getTypes()
    },
    computed: mapState({
        dataSource: state => state.Questionnaire.questionnaireList,
        page: state => state.Questionnaire.questionnairePage,
        types: state => state.Questionnaire.typeList
    }),
    methods: {
        ...mapActions(['saveList', 'saveTypes']),
        getTypes() {
          listTypeAllApi().then(res => {
            if (res.code === '000000') {
              this.saveTypes(res)
            } else {
              this.$message.error(res.message)
            }
          }, () => {
            this.$message.error('网络错误')
          })
        },
        allType(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.searchKey !== '') {
                params.searchKey = this.searchKey
            }
            listApi({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.saveList({
                        ...res,
                        number
                    })
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message) )
        },
        search() {
            this.allType(this.page.number)
        },
        edit(row) {
            this.dialogFormVisible = true
            this.title = '修改问卷'
            this.addForm = row
        },
        subject(row) {
          this.dialogFormAddVisible = true
          this.currentId = row.id
          this.options = row.options
        },
        editSubject(row) {
          this.$router.push({
              path: `/questionnaireSubject?id=${row.id}`
          });
        },
        deleSubject(index) {
          this.options.splice(index, 1)
        },
        addSubject() {
          this.options.push({})
        },
        //提交题目
        submitSubject() {
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    console.log(this.currentId, this.addOptions, this.options)
                    const params = {
                        qId: this.currentId,
                        ...this.addOptions
                    }
                    if (this.options.length > 0) {
                        const data = this.options.map((item, index) => {
                        return {
                            code: this.codes[index],
                            content: item.content
                        }
                        })
                        params.options = JSON.stringify(data)
                    }
                    addSubjectForQuestionApi({ ...params }).then(res => {
                        this.dialogFormAddVisible = false
                        if (res.code === '000000') {
                        this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        this.allType(this.page.number)
                        } else {
                        this.$message.error(res.message)
                        }
                    }, () => this.$message.error('网络错误'))
                }
            })
        },
        handleCurrentChange(val) {
            this.allType(val)
        },
        stateFormatter(row) {
            const state = row.state
            return state === 1 ? '启用' : '禁用'
        },
        delNotice(row) {
            this.$confirm('此操作将永久删除该名称, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteApi({ ids: row.id }).then(res => {
                    if (res.code === '000000') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.allType(this.page.number)
                    } else {
                        this.$message.error(res.message)
                    }   
                }, err => this.$message.error(err.message))
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        add() {
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    if (this.addForm.id) {
                        this.updateType() 
                    } else {
                        this.addAction()
                    }
                }
            })
        },
        addAction() {
            this.dialogFormVisible = false
            addApi({ ...this.addForm }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('添加成功')
                    this.allType(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message))
        },
        updateType() {
            this.dialogFormVisible = false
            const params = this.addForm
            updateApi({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('修改成功')
                    this.allType(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error(err.message))
        },
        addType() {
            this.dialogFormVisible = true
            this.title = '新增问卷'
            this.addForm = {}
        },
        switchChange(row) {
          disableApi({
            ids: row.id, 
            state: row.state ? '0' : '1' 
          }).then(res => {
            if (res.code === '000000') {
              this.$message.success('修改成功')
              this.allType(this.page.number)
            } else {
              this.$message.error(res.message)
            }
          }, () => {
            this.$message.error('网络错误')
          })
        }
    }
}
</script>
<style lang="less" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
.options {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  :global{
    .el-input {
      width: 900px;
    }
  }
}
</style>
